package com.example.manager.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.example.manager.entity.Teacher;
import com.example.manager.repository.TeacherRepository;

@Service
@Transactional
public class TeacherServiceImpl implements TeacherService {
	
	@Autowired
	private TeacherRepository teacherRepository;

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<Teacher> getAllTeacher() {
		List<Teacher> teacher = teacherRepository.findAll();
		return teacher;
		
	}

	@Override
	public Teacher getTeacherByTid(String tid) {
		Teacher teacher = teacherRepository.findById(tid).get();
		return teacher;
		
	}

	@Override
	public String editTeacher(Teacher teacher) {
		String tid = teacher.getTid();
		Teacher t = teacherRepository.getOne(tid);
		String name = teacher.getName();
		String password = teacher.getPassword();
		if(name==null||name.length()==0||password==null||password.length()==0) {
			
			return "imcomplete info";
		
		}
		t.setName(name);
		t.setPassword(password);
		if(teacherRepository.existsById(tid)) {
			
			teacherRepository.save(t);
			return "success";
		}else {
			
			return "fail";
			
		}
		
	}

	@Override
	public String deleteTeacher(String tid) {
		if(teacherRepository.existsById(tid)) {
			teacherRepository.deleteById(tid);
			return "success";
		}else {
			return "fail";
		}
	}

	@Override
	public String addTeacher(Teacher teacher) {
		String tid = teacher.getTid();
		String name = teacher.getName();
		String password = teacher.getPassword();
		if(tid==null||tid.length()==0||name==null||name.length()==0||password==null||password.length()==0) {
			return "incomplete info";
		}
		if(teacherRepository.existsById(tid)) {
			return "id exsists";
		}
		else {
			teacherRepository.save(teacher);
			return "success";
			
		}
	}

}
